# -*- encoding: utf-8 -*-
import re
import datetime
from rest_framework import serializers
from django.contrib.auth import get_user_model
from rest_framework.validators import UniqueValidator

from .models import VerifyCode
from Shop.settings import REGEX_MOBILE

User = get_user_model()


class SmsSerializer(serializers.ModelSerializer):
    class Meta:
        model = VerifyCode
        fields = ['mobile', ]

    def validate_mobile(self, mobile):
        """验证手机号码"""
        if User.objects.filter(mobile=mobile).count():
            raise serializers.ValidationError('用户已经存在.')

        if not re.match(REGEX_MOBILE, mobile):
            raise serializers.ValidationError('手机号码非法.')

        # 验证发送频率
        one_minute_ago = datetime.datetime.now() - datetime.timedelta(minutes=1)
        if VerifyCode.objects.filter(add_time__gt=one_minute_ago, mobile=mobile):
            raise serializers.ValidationError('未超过60s再次发送.')

        return mobile


class RegisterSerializer(serializers.ModelSerializer):
    code = serializers.CharField(max_length=4, min_length=4, required=True, label='验证码', write_only=True,
                                 error_messages={
                                     "blank": '请输入验证码',
                                     "required": '请输入验证码',
                                     "max_length": '验证码格式错误',
                                     "min_length": '验证码格式错误'
                                 },
                                 )  # userprofile中没有code

    username = serializers.CharField(label="用户名", required=True, allow_blank=False,
                                     validators=[UniqueValidator(queryset=User.objects.all(), message="用户已经存在")])

    password = serializers.CharField(
        style={'input_type': 'password'}, label="密码", write_only=True,
    )

    # 设置write_only, 验证后不会序列化返回

    class Meta:
        model = User
        fields = ['username', 'code', 'mobile', 'password']

    def validate_code(self, code):
        verify_records = VerifyCode.objects.filter(mobile=self.initial_data['username']).order_by("-add_time")
        if verify_records:
            last_record = verify_records[0]

            five_minutes_ago = datetime.datetime.now() - datetime.timedelta(minutes=5)
            if five_minutes_ago > last_record.add_time:
                raise serializers.ValidationError("验证码过期.")

            if last_record.code != code:
                raise serializers.ValidationError("验证码错误.")
        else:
            raise serializers.ValidationError("验证码错误.")

    def validate(self, attrs):
        attrs["mobile"] = attrs["username"]
        del attrs["code"]
        return attrs

    # 使用信号量
    # def create(self, validated_data):
    #     user = super(RegisterSerializer, self).create(validated_data=validated_data)
    #     user.set_password(validated_data['password'])
    #     user.save()
    #     return user
